package controllers;

import java.util.LinkedList;
import java.util.List;

import models.Log;
import models.Notification;
import models.User;
import models.UserRoleProject;
import play.data.validation.Required;
import play.libs.Codec;
import play.libs.Crypto;
import play.libs.Images;
import play.libs.Mail;
import play.mvc.Controller;

public class Registration extends Controller {

	static boolean regStatus = false;
	static String user_name;
	static String captcha;
	static boolean registered = false;

	/**
	 * @param firstName
	 * @param middleName
	 * @param lastName
	 * @param username
	 * @param password
	 * @param confirm_password
	 * @param email
	 * @param phone
	 * @param address
	 * @param city
	 * @param country
	 * @param code
	 * @param randomID
	 *            This method takes all user data entered in the registration
	 *            form and adds the user to the database
	 */
	public static void register(@Required String firstName, String middleName,
			@Required String lastName, @Required String username,
			@Required String password, @Required String confirm_password,
			@Required String email, String phone, String address, String city,
			String country, @Required String code, String randomID) {

		boolean unique = true;
		boolean unique2 = true;
		List<User> userNames = User.find("byUserName", username).fetch() ;
		List<User> emails = User.find("byEmail", username).fetch() ;
		if(userNames.size() != 0)
		{
			unique = false ;
		}
		if(emails.size() != 0)
		{
			unique2 = false ;
		}
		validation.equals(code, captcha);
		if (!unique && username != null) {
			params.flash();
			flash
					.error("This username is already in use, please choose another one");
			if (!regStatus)
				regPage();
			else
				regPage2();

		} else if (!unique2) {
			params.flash();
			flash
					.error("This email is already in use, please choose another one");
			if (!regStatus)
				regPage();
			else
				regPage2();

		}

		else if (validation.hasErrors()) {
			params.flash();
			flash.error("The code you entered is invalid");

			if (!regStatus)
				regPage();
			else
				regPage2();
		} else {
			if (phone.equals(""))
				phone = "0";
			User user = new User(firstName, middleName, lastName, username,
					password, email, phone, address, city, country, null);

			user.isDeactivated = true;
			user_name = username;
			registered = true;

			user.save();
			
			String userId = Crypto.encryptAES(user.getEntityId().toString());

			String link = String.format(
					"http://coolscrum.selfip.com/registration/activate?userId=%s",
					userId);

			String message = String
					.format(
							"Hello %s,\nWelcome to Scrum Cool Tool\n\nYour Username is: %s\nYour Password is: %s\n\nTo activate your account, click on the following link: %s",
							user.firstName, user.userName, user.password, link);

			Mail.send("coolSoft@SMT.com", user.email, "Registration", message);

			User systemAdmin = UserRoleProject
					.find(
							"select u.user from UserRoleProject u where u.role.title = 'System Admin'")
					.first();

			String notify = String.format("%s have registered to the system.",
					user.userName);

			new Notification((Long) systemAdmin.getEntityId(), "Registration",
					notify).save();

			new Log((Long) user.getEntityId(), null, null, notify, null, null)
					.save();

			render("Registration/registered.html");

		}

	}

	/**
	 * @param userId
	 * 
	 *            This method activates the user account when he clicks on the
	 *            link in his mail
	 */
	public static void activate(String userId) {
		
		long uId = Long.parseLong(Crypto.decryptAES(userId + ""));
		User user = User.findById(uId);
		user.isDeactivated = false;
		user.save();
		Admin.index();
	}

	/**
	 * This method renders the registration page and it turn the boolean
	 * variable regStatus to false which means this user is a normal guest
	 */
	public static void regPage() {
		regStatus = false;
		render("Registration/registration.html");
	}

	/**
	 * This method renders the registration page and it turn the boolean
	 * variable regStatus to true which means this user is a guest invited to
	 * join a project
	 */
	public static void regPage2() {
		regStatus = true;
		render("Registration/registration.html");
	}

	/**
	 * @param id
	 *            This method generates the image of the captcha and renders it
	 *            in the registration page
	 */
	public static void captcha(String id) {
		Images.Captcha image = Images.captcha();
		captcha = image.getText();
		renderBinary(image);
	}

	/**
	 * @param id
	 *            This method generates a random id that generates random
	 *            captcha images
	 */
	/*public static void show() {
		String randomID = Codec.UUID();
		render(randomID);
	}*/
}
